
package com.cjstudio.bluetooth;

import java.lang.ref.WeakReference;

import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.util.Log;

/**
 * Provides "background" audio playback capabilities, allowing the
 * user to switch between activities without stopping playback.
 */
public class BluetoothService extends Service {
    private static final String LOGTAG = "BluetoothService";
    
    private int mServiceStartId = -1;
    private boolean mServiceInUse = false;


    private Handler mBluetoothServiceHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
            /*
                case :
                    break;
                default:
                    break;
             */
            }
        }
    };

    private BroadcastReceiver mIntentReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            String cmd = intent.getStringExtra("command");
            /*
            MusicUtils.debugLog("mIntentReceiver.onReceive " + action + " / " + cmd);
            if (CMDNEXT.equals(cmd) || NEXT_ACTION.equals(action)) {
                next(true);
            } else if (CMDPREVIOUS.equals(cmd) || PREVIOUS_ACTION.equals(action)) {
                prev();
            } else if (CMDTOGGLEPAUSE.equals(cmd) || TOGGLEPAUSE_ACTION.equals(action)) {
                if (isPlaying()) {
                    pause();
                    mPausedByTransientLossOfFocus = false;
                } else {
                    play();
                }
            } else if (CMDPAUSE.equals(cmd) || PAUSE_ACTION.equals(action)) {
                pause();
                mPausedByTransientLossOfFocus = false;
            } else if (CMDSTOP.equals(cmd)) {
                pause();
                mPausedByTransientLossOfFocus = false;
                seek(0);
            } else if (MediaAppWidgetProvider.CMDAPPWIDGETUPDATE.equals(cmd)) {
                // Someone asked us to refresh a set of specific widgets, probably
                // because they were just added.
                int[] appWidgetIds = intent.getIntArrayExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS);
                mAppWidgetProvider.performUpdate(MediaPlaybackService.this, appWidgetIds);
            }
            */
        }
    };


    public BluetoothService() {
    	
    }

    @Override
    public void onCreate() {
		Log.d(LOGTAG, "onCreate()");

        super.onCreate();
        
        /*
        IntentFilter commandFilter = new IntentFilter();
        commandFilter.addAction(SERVICECMD);
        commandFilter.addAction(TOGGLEPAUSE_ACTION);
        commandFilter.addAction(PAUSE_ACTION);
        commandFilter.addAction(NEXT_ACTION);
        commandFilter.addAction(PREVIOUS_ACTION);
        registerReceiver(mIntentReceiver, commandFilter);
        */
        /*
        PowerManager pm = (PowerManager)getSystemService(Context.POWER_SERVICE);
        mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, this.getClass().getName());
        mWakeLock.setReferenceCounted(false);
        */
        
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

		if (mBluetoothAdapter == null) {
			Log.d(LOGTAG, "Bluetooth Unabled.");
			return;
		}
        
        
        mSerialService = new BluetoothSerialService(this, null);
    }

    @Override
    public void onDestroy() {
		Log.d(LOGTAG, "onDestroy()");

        // Check that we're not being destroyed while something is still playing.
        if (isScanning()) {
            Log.e(LOGTAG, "Service being destroyed while still playing.");
        }
        
        if (mSerialService != null)
        		mSerialService.stop();
        
        super.onDestroy();
    }
    
    private boolean isScanning() {
		// TODO Auto-generated method stub
		return mServiceInUse;//!
	}
    
    public void writeChar(int c) {
    		if(mSerialService.mConnectedThread != null) {
    			mSerialService.mConnectedThread.writeChar(c);
    		}
    }

	@Override
    public IBinder onBind(Intent intent) {
		Log.d(LOGTAG, "onBind()");
		if (getConnectionState() == BluetoothSerialService.STATE_NONE) {
	    		// Get the device MAC address
	        BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
	        // Attempt to connect to the device
	        mSerialService.connect(device);
	    	}
	    	else {
	        	if (getConnectionState() == BluetoothSerialService.STATE_CONNECTED) {
	        		mSerialService.stop();
		    		mSerialService.start();
	        	}
	    }
		
		if (mSerialService != null) {
		    	// Only if the state is STATE_NONE, do we know that we haven't started already
		    	if (mSerialService.getState() == BluetoothSerialService.STATE_NONE) {
		    		// Start the Bluetooth chat services
		    		mSerialService.start();
		    	}
	    }
			
        mServiceInUse = true;
        return mBinder;
    }

    @Override
    public void onRebind(Intent intent) {
		Log.d(LOGTAG, "onRebind()");
    		super.onRebind(intent);
    		
        mServiceInUse = true;
        
        if (mSerialService != null) {
		    	// Only if the state is STATE_NONE, do we know that we haven't started already
		    	if (mSerialService.getState() == BluetoothSerialService.STATE_NONE) {
		    		// Start the Bluetooth chat services
		    		mSerialService.start();
		    	}
	    }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        mServiceStartId = startId;

        if (intent != null) {
            String action = intent.getAction();
            String cmd = intent.getStringExtra("command");
//            MusicUtils.debugLog("onStartCommand " + action + " / " + cmd);

            /*
            if (CMDNEXT.equals(cmd) || NEXT_ACTION.equals(action)) {
                next(true);
            } else if (CMDPREVIOUS.equals(cmd) || PREVIOUS_ACTION.equals(action)) {
                if (position() < 2000) {
                    prev();
                } else {
                    seek(0);
                    play();
                }
            } else if (CMDTOGGLEPAUSE.equals(cmd) || TOGGLEPAUSE_ACTION.equals(action)) {
                if (isPlaying()) {
                    pause();
                    mPausedByTransientLossOfFocus = false;
                } else {
                    play();
                }
            } else if (CMDPAUSE.equals(cmd) || PAUSE_ACTION.equals(action)) {
                pause();
                mPausedByTransientLossOfFocus = false;
            } else if (CMDSTOP.equals(cmd)) {
                pause();
                mPausedByTransientLossOfFocus = false;
                seek(0);
            }
            */
        }
        
        return START_STICKY;
    }
    
    @Override
    public boolean onUnbind(Intent intent) {
    		Log.d(LOGTAG, "onUnbind()");
        mServiceInUse = false;
        
        /*
        if (isScanning()) {
            // something is currently playing, or will be playing once 
            // an in-progress action requesting audio focus ends, so don't stop the service now.
            return true;
        }
        */
        
        //OK to stop the service right now
        stopSelf(mServiceStartId);
        return true;
    }
    

    /*
     * By making this a static class with a WeakReference to the Service, we
     * ensure that the Service can be GCd even when the system process still
     * has a remote reference to the stub.
     */
    static class ServiceStub extends IBluetoothService.Stub {
        WeakReference<BluetoothService> mService;
        
        ServiceStub(BluetoothService service) {
            mService = new WeakReference<BluetoothService>(service);
        }

		@Override
		public void writeChar(int c) throws RemoteException {
			mService.get().writeChar(c);
		}
    }

    private final IBinder mBinder = new ServiceStub(this);
    
	private BluetoothAdapter mBluetoothAdapter = null;
    private static BluetoothSerialService mSerialService = null;
    
    private static final String address = "00:06:66:05:01:59";
    private static final String address1 = "00:06:66:04:13:D6";
    
    public int getConnectionState() {
		return mSerialService.getState();
	}
}
